<template>
  <div>
    <jy-dialog title="器具" :visible.sync="open" width="800px" append-to-body>
      <el-row :gutter="10">
        <el-col :span="6" :xs="24">
          <div class="dialog-table-border">
            <el-input v-model="syTypeName" placeholder="请输入器具名称" clearable size="small" prefix-icon="el-icon-search"
              style="margin-bottom: 20px" />
            <el-tree class="dialog-tree" :data="options" :props="defaultProps" :expand-on-click-node="false"
              :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current
              @node-click="handleNodeClick">
              <div slot-scope="{node, data}" class="custom-tree-node" :class="{ 'tree-disabled': !node.isLeaf }"
                :title="node.label" v-text="node.label"></div>
            </el-tree>
          </div>
        </el-col>

        <el-col :span="18" :xs="24">
          <div class="dialog-table-border">
            <el-row :gutter="10" class="mb8 sycs-add flex align-center">
              <el-col :span="1.5">
                <el-input v-model="queryParams.hh" placeholder="请输入试验器具名称" size="small" clearable
                  @keyup.enter.native="handleQuery" />
              </el-col>
              <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="primary" plain size="mini" @click="handleAdd">新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="primary" plain :disabled="!(currentRow && currentRow.detailId)" size="mini"
                  @click="handleUpdate">修改</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="primary" plain :disabled="!(currentRow && currentRow.detailId)" size="mini"
                  @click="handleDelete">删除</el-button>
              </el-col>
            </el-row>
            <el-table border stripe v-loading="loading" :data="baQjDetailList" table-layout="auto"
              @current-change="handleCurrentChange" :row-class-name="tableRowClassName">
              <el-table-column width="50" label="选择" class-name="radio-border">
                <template slot-scope="scope">
                  <el-radio :label="scope.row.detailId" v-model="currentDetailId"
                    :disabled="hehIds.includes(scope.row.detailId)">{{ '' }}</el-radio>
                </template>
              </el-table-column>
              <el-table-column label="盒（筒）号" align="center" prop="hh" min-width="120" show-overflow-tooltip />
              <el-table-column label="类别" align="center" prop="syQjName" min-width="100" show-overflow-tooltip />
              <el-table-column label="质量（g）" align="center" prop="quality" min-width="100" show-overflow-tooltip />
              <el-table-column label="筒容积（cm3）" align="center" prop="tongrj" min-width="120" show-overflow-tooltip
                v-if="currentNode.label && currentNode.label.indexOf('筒') != -1" />
            </el-table>
            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize" :autoScroll="false" @pagination="getList"
              :layout="'total, prev, pager, next, jumper'" :pagerCount="5" />
          </div>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="submitIndex">确 定</el-button>
        <el-button size="small" @click="cancel">取 消</el-button>
      </div>
      <ba-qj-detail-add-or-update ref="addOrUpdateRef" :current-node="currentNode" @callBack="handleQuery" />
    </jy-dialog>
  </div>
</template>
<script>
import { qjTree, page, usablePage, delBaQjDetail } from "@/api/sycs/baQjDetail";
import store from "@/store";
import { mapGetters } from "vuex";
import BaQjDetailAddOrUpdate from "./BaQjDetailAddOrUpdate.vue";
export default {
  components: { BaQjDetailAddOrUpdate },
  name: "BaQjDetailVIew",
  data () {
    return {
      title: "",
      open: false,
      loading: false,
      // 总条数
      total: 0,
      // 器具明细表表格数据
      baQjDetailList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        qjId: undefined,
        remark: undefined,
        hh: undefined
      },
      syTypeName: undefined,
      options: [],
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 当前树节点
      currentNode: {},
      currentRow: {},
      currentDetailId: undefined,
      type: "",
      hehIds: []
    };
  },
  props: {
    excelId: {
      type: [String, Number],
      default: ""
    },
    shiyjcrq: {
      type: String,
      default: ""
    }
  },
  computed: {
    ...mapGetters(["deptId"])
  },
  watch: {
    // 根据名称筛选树
    syTypeName (val) {
      this.$refs.tree.filter(val);
    }
  },
  created () { },
  mounted () { },
  methods: {
    init (type, hehIds) {
      this.type = type;
      this.hehIds = hehIds || [];
      if (!this.options || this.options.length == 0) {
        this.getDeptTree();
      }
      this.handleQuery();
      this.open = true;
    },
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 查询器具明细表列表 */
    getList () {
      if (!this.deptId) {
        this.$alert("", "请选择试验室", {
          confirmButtonText: "确定",
          type: "warning",
          center: true
        });
        return;
      }
      // 空表打印
      const printEmpty = store.state.reportForms.printEmpty;
      if ((!this.queryParams.qjId || !this.excelId || !this.shiyjcrq) && !printEmpty) {
        return;
      }
      if (!this.queryParams.qjId) {
        return;
      }
      this.loading = true;
      this.queryParams = {
        ...this.queryParams,
        deptId: this.deptId,
        excelId: printEmpty ? this.$defaultExcelId : this.excelId,
        shiyjcrq: printEmpty ? this.formatDate(new Date()) : this.shiyjcrq
      };
      usablePage(this.queryParams).then((response) => {
        this.baQjDetailList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询树结构 */
    getDeptTree () {
      qjTree().then((response) => {
        this.options = response.data;
        // if (this.options && this.options.length > 0 && this.options[0].children && this.options[0].children.length > 0 && this.options[0].children[0] && this.options[0].children[0].id) {
        //   this.queryParams.qjId = this.options[0].children[0].id + '';
        //   this.getList()
        // }
      });
    },
    tableRowClassName ({ row, rowIndex }) {
      if (this.hehIds.includes(row.detailId)) {
        return "no-select";
      }
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.$refs.addOrUpdateRef.init(null, this.queryParams.qjId);
    },
    /** 修改按钮操作 */
    handleUpdate () {
      const detailId = this.currentRow.detailId;
      this.$refs.addOrUpdateRef.init(detailId);
    },
    /** 删除按钮操作 */
    handleDelete () {
      const detailIds = this.currentRow.detailId;
      this.$modal
        .confirm(`是否确认删除盒(筒)号${this.currentRow.hh}？`)
        .then(() => {
          this.loading = true;
          return delBaQjDetail(detailIds);
        })
        .then(() => {
          this.loading = false;
          this.getDeptTree();
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { })
        .finally(() => {
          this.loading = false;
        });
    },

    // 筛选节点
    filterNode (value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick (data, node, self) {
      // 如果当前节点不是最底层，则不允许选择
      if (!node.isLeaf) {
        this.$refs.tree.setCurrentKey(null);
        return;
      }
      this.$set(this.currentNode, "id", data.id);
      this.$set(this.currentNode, "label", data.label);
      this.queryParams.qjId = data.id;
      this.getList();
    },
    handleCurrentChange (val) {
      if (val && val?.detailId && this.hehIds && this.hehIds.includes(val.detailId)) {
        return;
      }
      this.currentRow = val;
      this.currentDetailId = val?.detailId;
    },
    submitIndex () {
      this.$emit("select", this.type, this.currentRow);
      this.cancel();
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        detailId: undefined,
        qjId: undefined,
        remark: undefined,
        hh: undefined,
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
      this.type = "";
      this.currentRow = {};
      this.currentDetailId = undefined;
    },
    formatDate (date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0"); // 月份从0开始，所以需要+1
      const day = date.getDate().toString().padStart(2, "0");
      return `${year}年${month}月${day}日`;
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .radio-border .cell {
  display: flex;
  justify-content: center;
  padding-right: 0;
}

.tree-disabled {
  color: #afafaf;
}

::v-deep .no-select {
  cursor: not-allowed;

  .cell {
    pointer-events: none;

    /* 防止鼠标点击事件 */
    .el-checkbox__inner {
      background-color: #f2f6fc;
      border-color: #dcdfe6;

      &::after {
        border-color: #c0c4cc;
      }
    }
  }
}
</style>
